package luke.audio.metadata;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 音频元数据读取器类，用于读取音频文件的标签信息
 * 如艺术家、标题、专辑等元数据
 */
public class AudioMetadataReader {

    /**
     * 音频元数据信息类
     */
    public static class AudioMetadata {
        private String title;
        private String artist;
        private String album;
        private String year;
        private String genre;
        private String trackNumber;
        private String duration; // 时长
        private String bitrate;  // 比特率
        private String sampleRate; // 采样率
        private String format; // 音频格式

        // Getters and Setters
        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getArtist() {
            return artist;
        }

        public void setArtist(String artist) {
            this.artist = artist;
        }

        public String getAlbum() {
            return album;
        }

        public void setAlbum(String album) {
            this.album = album;
        }

        public String getYear() {
            return year;
        }

        public void setYear(String year) {
            this.year = year;
        }

        public String getGenre() {
            return genre;
        }

        public void setGenre(String genre) {
            this.genre = genre;
        }

        public String getTrackNumber() {
            return trackNumber;
        }

        public void setTrackNumber(String trackNumber) {
            this.trackNumber = trackNumber;
        }

        public String getDuration() {
            return duration;
        }

        public void setDuration(String duration) {
            this.duration = duration;
        }

        public String getBitrate() {
            return bitrate;
        }

        public void setBitrate(String bitrate) {
            this.bitrate = bitrate;
        }

        public String getSampleRate() {
            return sampleRate;
        }

        public void setSampleRate(String sampleRate) {
            this.sampleRate = sampleRate;
        }

        public String getFormat() {
            return format;
        }

        public void setFormat(String format) {
            this.format = format;
        }

        @Override
        public String toString() {
            Map<String, String> metadataMap = new HashMap<>();
            metadataMap.put("Title", title);
            metadataMap.put("Artist", artist);
            metadataMap.put("Album", album);
            metadataMap.put("Year", year);
            metadataMap.put("Genre", genre);
            metadataMap.put("Track Number", trackNumber);
            metadataMap.put("Duration", duration);
            metadataMap.put("Bitrate", bitrate);
            metadataMap.put("Sample Rate", sampleRate);
            metadataMap.put("Format", format);

            StringBuilder sb = new StringBuilder("Audio Metadata:\n");
            for (Map.Entry<String, String> entry : metadataMap.entrySet()) {
                if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                    sb.append("  ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
                }
            }
            return sb.toString();
        }
    }

    /**
     * 从音频文件路径读取元数据
     *
     * @param filePath 音频文件路径
     * @return AudioMetadata对象，包含音频文件的元数据信息
     */
    public static AudioMetadata readMetadata(String filePath) {
        return readMetadata(new File(filePath));
    }

    /**
     * 从音频文件读取元数据
     *
     * @param audioFile 音频文件
     * @return AudioMetadata对象，包含音频文件的元数据信息
     */
    public static AudioMetadata readMetadata(File audioFile) {
        AudioMetadata metadata = new AudioMetadata();

        try {
            // 使用jaudiotagger读取音频文件
            AudioFile audioFileObj = AudioFileIO.read(audioFile);
            Tag tag = audioFileObj.getTag();

            // 读取基本标签信息
            if (tag != null) {
                metadata.setTitle(tag.getFirst(FieldKey.TITLE));
                metadata.setArtist(tag.getFirst(FieldKey.ARTIST));
                metadata.setAlbum(tag.getFirst(FieldKey.ALBUM));
                metadata.setYear(tag.getFirst(FieldKey.YEAR));
                metadata.setGenre(tag.getFirst(FieldKey.GENRE));
                metadata.setTrackNumber(tag.getFirst(FieldKey.TRACK));
            }

            // 读取技术信息
            metadata.setDuration(formatDuration(audioFileObj.getAudioHeader().getTrackLength()));
            metadata.setBitrate(audioFileObj.getAudioHeader().getBitRate());
            metadata.setSampleRate(audioFileObj.getAudioHeader().getSampleRate());
            metadata.setFormat(audioFileObj.getAudioHeader().getFormat());

        } catch (Exception e) {
            System.err.println("读取音频文件元数据时出错: " + e.getMessage());
            e.printStackTrace();
        }

        return metadata;
    }

    /**
     * 格式化时长（秒转为分钟:秒格式）
     *
     * @param seconds 时长（秒）
     * @return 格式化后的时长字符串（mm:ss）
     */
    private static String formatDuration(int seconds) {
        if (seconds <= 0) {
            return "";
        }
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%d:%02d", minutes, remainingSeconds);
    }
}